package myJs.cps

import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import myJs.Utils.vRef
import myJs.myPkg.reactHookForm._
import org.scalajs.dom.html

import scala.scalajs.js

/** Created by yz on 15/9/2023
  */
object PureInputCp {

  case class Props(
      name: String = "",
      readOnly: Boolean = false,
      required: Boolean = true,
      registerOptions: RegisterOptions = RegisterOptions(),
      onChange: String => Callback=(v:String)=>Callback{},
      showValidate: Boolean = true,
      value: String = "",
      width: String = "",
      placeHolder: String = "",
      `type`: String = "",
      selfClassName: String = "",
      onFocus: js.UndefOr[html.Input => Unit] = js.undefined
  ){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>

    val useController = ReactHookForm.useController(options =
      UseControllerOptions(
        name = props.name,
        rules = props.registerOptions,
        defaultValue = props.value
      )
    )

    val field = useController.field
    val fieldState = useController.fieldState
    val useForm = ReactHookForm.useFormContext()

    object FTool {

      def onChange(e: ReactEventFromInput) =  {
        val v = e.target.value
        field.onChange(v)
        props.onChange(v)
      }

      def focusF = (e:ReactEventFromInput) => Callback{
        val inputE = e.target
        props.onFocus.foreach(_(inputE))
      }

    }

    Fragment(
      input(
        className := "form-control",
        name := field.name,
        placeholder := props.placeHolder,
        value := props.value,
        onChange ==> FTool.onChange,
        `type` := props.`type`,
        vRef := field.ref,
        onFocus ==> FTool.focusF,
      ),
      if (props.showValidate && fieldState.error.isDefined) {
        small(className := "help-block", fieldState.error.get.message)
      } else EmptyVdom
    )

  }

}
